package com.itheima.task;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

@Component
@Slf4j
public class HealthBackendTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 进行redis垃圾图片的清理逻辑
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public  void clearImg(){

        Long picSize = redisTemplate.opsForSet().size(RedisConstant.SETMEAL_PIC_RESOURCES);
        Long picDbSize=redisTemplate.opsForSet().size(RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        if (picSize>picDbSize){
            //获取两个redis的差集
            Set differencePics = redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
            for (Object differencePic : differencePics) {
                //阿里云删除对应的图片
                aliOssUtil.delete(differencePic.toString());
                //pic集合删除对应的图片
                redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES, differencePic);
            }
            //TODO:删除对应的两个集合?

        }
    }

}
